package com.mdp.im.core.publish;

import com.mdp.im.core.plugin.api.StorePlugin;
import com.mdp.im.core.utils.StoreQueueNames;
import com.mdp.im.core.publish.api.StorePublisher;
import com.mdp.mq.queue.Push;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class StoreMessagePublisher implements StorePublisher {
	

    private static final Logger logger = LoggerFactory.getLogger(StoreMessagePublisher.class);

    @Autowired(required = false)
    List<StorePlugin> storePlugins;


    @Autowired
	Push push;
 


   public void publishPrichatMessageToDbQueue(String message) {
	   boolean isGo=beforeStore(message);
	   if(isGo){
		   push.leftPush(StoreQueueNames.im_prichat_message_queue_name,message);
	   }
	   afterStore(isGo,message);

	}


	public void publishGroupMessageToDbQueue(String message) {
		boolean isGo=beforeStore(message);
		if(isGo){
			push.leftPush(StoreQueueNames.im_group_message_queue_name,message);
		}
		afterStore(isGo,message);

	}



	public void publishSysMessageToDbQueue(String message) {
		boolean isGo=beforeStore(message);
		if(isGo){
			push.leftPush(StoreQueueNames.im_sys_message_queue_name,message);
		}
		afterStore(isGo,message);

	}

	boolean beforeStore(String message){
   		if(storePlugins!=null && storePlugins.size()>0){
   			boolean isGo=true;
			for (StorePlugin storePlugin : storePlugins) {
				if(isGo){
					isGo=storePlugin.beforeStore(message);
				}else if(isGo==false){
					storePlugin.beforeStore(message);
				}
			}
			return isGo;
		}else{
   			return true;
		}
	}
	void afterStore(boolean isGo,String message){
		if(storePlugins!=null && storePlugins.size()>0){
			for (StorePlugin storePlugin : storePlugins) {
				storePlugin.afterStore(isGo,message);
			}
		}
	}

}
